package com.logic.modular.game.shop.domain;

import com.logic.comment.util.RedisUtils;
import com.logic.config.netty.web.service.MessageService;
import com.comment.pojo.domain.logic.core.CoreShopGoods;
import com.logic.modular.gameCore.shop.service.CoreShopGoodsServiceImpl;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class PlayerShop {
    @ApiModelProperty
    private Long playerId;
    @ApiModelProperty("商品列表")
    private Map<String, CoreShopGoods> goodsMap;
    @ApiModelProperty("上次刷新时间,自然刷新")
    private long equipLastRefreshTime;
    @ApiModelProperty("今日刷新次数")
    private int equipRefreshCount;

    public void save() {
        String key = String.format("player:%d:shop", getPlayerId());
        RedisUtils.redisUtils().set(key, this, 24, TimeUnit.HOURS);
        MessageService.sendMessageToUser(playerId, MessageService.updateJsonObject("playerShop", this));
    }

    public static PlayerShop get(Long playerId) {
        String key = String.format("player:%d:shop", playerId);
        return (PlayerShop) RedisUtils.redisUtils().get(key);
    }

    /**
     * 自然刷新装备
     */
    public void refreshEquip() {
        // 玩家商店数据
        Map<Integer, List<CoreShopGoods>> collect = getGoodsMap().values().stream()
                .collect(Collectors.groupingBy(CoreShopGoods::getType));
        // 获取随机装备
        Set<CoreShopGoods> coreShopGoodsSet = CoreShopGoodsServiceImpl.obtainEquip();
        List<CoreShopGoods> shopGoodsList = coreShopGoodsSet.stream().peek(item -> item.setBuyNum(0)).collect(Collectors.toList());
        collect.put(4, shopGoodsList);
        // 更新商品数据
        goodsMap = collect.values().stream()
                .flatMap(Collection::stream)
                .collect(Collectors.toMap(item -> item.getId().toString(), item -> item));;
        equipLastRefreshTime = System.currentTimeMillis();
        save();
    }
}
